package com.m1book.domain;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.m1book.domain.relation.InviteTrace;
import com.m1book.domain.user.Miser;
import com.m1book.domain.util.MailSender;
import com.m1book.repositories.relation.InviteTraceRepository;

/**
 * {@link InviteService}的实现类，实现了咪书网的邀请好友的功能。
 * @author Frankie
 *
 */
@Service
public class InviteServiceImpl implements InviteService {
	private static final Logger logger = LoggerFactory.getLogger(InviteServiceImpl.class);
	
	@Autowired
	private InviteTraceRepository inviteTraceRepository;

	@Override
	public String inviteByQQ(Miser miser, String qq, String inviteeName, String joinPath) {
		logger.info("miser id: " + miser.getId() + " try to invite friend by QQ number: " + qq);
		long inviteTime = System.currentTimeMillis();
		InviteTrace inviteTrace = new InviteTrace(miser, qq, inviteeName, inviteTime);
		inviteTraceRepository.save(inviteTrace);
		String inviteSN =  inviteTrace.getInviteSN();
		
		MailSender.sendInvite(joinPath, inviteSN, miser, qq, inviteeName);
		
		return inviteSN;
	}

	@Override
	public InviteTrace getInviteTrace(String inviteSN) throws InviteTraceNotExistException {
		InviteTrace inviteTrace = inviteTraceRepository.findByinviteSN(inviteSN);
		
		if(inviteTrace == null) {
			throw new InviteTraceNotExistException("not found invite trace by sn: " + inviteSN);
		}
		
		inviteTrace.setCheckTime(new Date());
		inviteTraceRepository.save(inviteTrace);
		
		return inviteTrace;
	}

}
